<template>
    <UxDialog :visible="visible" @close="visible = false">

        <div class="uploader">
            <!-- 文件添加框 -->
            <!-- <div ref="filebox" class="filebox"></div> -->

            <div class="drag-box" @dragenter="active = true" @dragleave="active = false" @dragover="fileDragover($event)" @drop="fileDrop($event)" :class="{active:active}">
                <svg-icon name="user-files-drag" />
                <span>Drop images here</span>
            </div>

            <div class="or"></div>

            <div class="input">
                <label>
                    <svg-icon name="user-files-upload" />
                    <span>Choose files</span>
                    <input type="file" multiple accept="image/jpeg,image/jpg,image/png" @change="fileClick($event)">
                </label>
            </div>

            <p>
                <svg-icon name="notify2" />
                <span>JPG or PNG format, max 50 MB</span>
            </p>
        </div>
    </UxDialog>
</template>
<script>
import Md5 from "js-md5";
import { mapGetters } from "vuex";
export default {
    props: {
        value: { type: Boolean, default: () => false },
        folder: { type: Number, default: 0 },
        uploaded: { type: Array, default: () => [] },
    },
    data () {
        return {
            active: false,
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        visible: {
            get () { return this.value },
            set (val) { this.$emit("input", val); }
        }
    },

    methods: {

        // 拖拽上传
        fileDragover (event) {
            event.preventDefault()
        },
        fileDrop (event) {
            event.preventDefault()
            this.active = false;
            this.uploadFiles(Array.prototype.slice.call(event.dataTransfer.files))
        },
        fileClick (event) {
            const files = Array.prototype.slice.call(event.target.files)
            this.uploadFiles(files)
            event.target.value = null;
        },

        // 上传
        uploadFiles (files) {

            // 01.图片预览失败: Network error. Please try again.
            // 02.不支持的文件格式（只支持png，jpeg，jpg）: Incorrect file format.
            // 03.图片不能大于50M: Uploaded image exceeds 50MB limit.
            // 04.图片上传失败（超过三次）: Network error. Please try again.
            // 05.生成缩略图失败: Network error. Please try again.
            // 06.图片绑定用户失败:  Network error. Please try again.

            const time = new Date().getTime();
            const options = []

            const promises = files.map((file, index) => {
                const option = {
                    type: "uploading",
                    folder_id: this.folder || '',
                    id: time + "-" + index,
                    img_type: file.type.replace("image/", ""),
                    img_name: file.name,
                    img_size: file.size,
                    img_url: "",
                    preview_url: '',
                    width: 1,
                    height: 1,
                    file: file,
                    image: null,
                    percent: 5,
                    error: '',
                };

                options.push(option)

                return this.getFileInfo(option)
                    .then(() => this.uploadToOSS(option))
                    .then(() => this.createThumb(option))
                    .then(() => this.bindUser(option))
                    .then(() => {
                        // 成功
                        option.type = "";
                        option.percent = 100;
                    }).catch(err => {
                        // 失败
                        option.type = "error";
                        option.error = err || 'Network error. Please try again.';

                        // 01.图片预览失败: Network error. Please try again.
                        // 02.不支持的文件格式（只支持png，jpeg，jpg）: Incorrect file format.
                        // 03.图片不能大于50M: Uploaded image exceeds 50MB limit.
                        // 04.图片上传失败（超过三次）: Network error. Please try again.
                        // 05.生成缩略图失败: Network error. Please try again.
                        // 06.图片绑定用户失败:  Network error. Please try again.

                        const map = new Map([
                            ['Incorrect file format.', 'Please upload files in jpg or png format.'],
                            ['Uploaded image exceeds 50MB limit.', ' Uploaded images should not exceed 50MB.'],
                        ])

                        const notify = '"' + option.img_name + '" upload failed. ' + (map.get(option.error) || '')
                        this.$uxMessage.error(notify);
                    })

            })

            this.visible = false;

            if (promises.length > 0) {
                // 如果正在搜索中，则退出搜索
                if (this.$parent.form.name) {
                    this.$parent.keywords = '';
                    this.$parent.getSearching()
                }
                this.$emit('update:uploaded', [...options, ...this.uploaded]);
                Promise.all(promises).then(() => this.$emit('reload'))
            }

        },


        // 获取文件信息
        getFileInfo (option) {

            // 获取图片
            const getImage = new Promise((resolve, reject) => {
                const _URL = window.URL || window.webkitURL;
                const img = new Image();
                img.onload = () => {
                    option.image = img;
                    option.width = img.width;
                    option.height = img.height;
                    resolve();
                };
                img.onerror = (error) => { reject('Network error. Please try again.') };
                img.src = _URL.createObjectURL(option.file);
            })

            // 获取文件信息
            const getMime = new Promise((resolve, reject) => {

                let blob = option.file.slice(0, 128);//仅获取前128字节。
                let reader = new FileReader();
                reader.onloadend = function (e) {
                    let arr = (new Uint8Array(e.target.result)).subarray(0, 200);
                    let header = "";
                    const mime = [//type:类型，h：16字节标识【根据需要，自行添加】
                        { type: 'image/png', h: '89504e47' },
                        { type: 'image/gif', h: '47494638' },
                        { type: 'image/jpeg', h: 'ffd8ffe0,ffd8ffe1,ffd8ffe2,ffd8ffe3,ffd8ffe8' },
                        { type: 'image/webp', h: '524946461c' },
                        { type: 'Windows Bitmap/bmp', h: '424D' },
                        { type: 'TIFF/tif', h: '49492A00' },
                        { type: 'CAD/dwg', h: '41433130' },
                        { type: 'Adobe Photoshop/psd', h: '384250' },
                    ]
                    const check = (header) => {
                        for (let i in mime) {
                            let arr = mime[i].h.split(',');
                            let offset = (mime[i].offset || -1) + 1;//偏移量
                            for (let j in arr) {
                                let byte = arr[j].toLowerCase().replace(/\s+/g, "");
                                if (header.indexOf(byte) == offset) {
                                    return mime[i].type;
                                }
                            }
                        }
                        return 'unknown';
                    }


                    for (let i = 0; i < arr.length; i++) {
                        header += arr[i].toString(16);
                    }

                    option.mime = check(header);
                    option.suffix = option.mime.replace(/^[\w\W]*\/(\w+)/, '$1')

                    if (/(png|jpe?g)$/i.test(option.suffix)) {
                        return resolve(option)
                    } else {
                        return reject('Incorrect file format.')
                    }

                }
                reader.readAsArrayBuffer(blob);
            })

            const maxsize = 1024 * 1024 * 50; // 不能上传超过50M的图片
            if (option.file.size > maxsize) {
                return Promise.reject('Uploaded image exceeds 50MB limit.')
            } else {
                return Promise.all([getImage, getMime])
            }

        },

        // 上传文件
        uploadToOSS (option) {

            const email = (this.userInfo || {}).email;
            const folder = email ? Md5(email) : 'noemail';
            const path = 'data/pod/file/' + folder;

            const time = new Date().getTime();
            const random = Math.random().toFixed(10).substr(2);
            const name = time + "-" + random + "." + option.img_type;

            const request = {
                file: option.file,
                name: name,
                path: path.replace(/\/+$/, '') + '/',
                onprogress (event) {
                    option.percent = 5 + parseInt(0.9 * event.percent);
                },
            };

            return new Promise((resolve, reject) => {
                this.$uploadToOSS(request, response => {
                    if (response.code === 0 && response.data) {
                        option.img_url = response.data || '';
                        resolve(option);
                    } else {
                        reject(response.msg || "Network error. Please try again.");
                    }
                })
            })

        },

        // 生成缩略图
        createThumb (option) {
            return new Promise((resolve, reject) => {
                this.$http("Drawer.createThumb", { fullname: option.img_url }).then((result) => {
                    if (!result || result.code !== 0) {
                        return reject("Network error. Please try again.");
                    } else {
                        option.preview_url = result.data;
                        resolve(option);
                    }
                }).catch(error => {
                    reject("Network error. Please try again.");
                })

            })
        },

        //  绑定用户图片
        bindUser (option) {
            // 绑定
            const request = {
                folder_id: option.folder_id,
                file_name: option.img_name,
                file_url: option.img_url,
                file_size: option.img_size,
                width: option.width,
                height: option.height,
                img_type: option.img_type,
                preview_url: option.preview_url,
            };
            return new Promise((resolve, reject) => {
                this.$http('Material.setMaterialBind', request).then(result => {
                    if (!result || result.code !== 0) {
                        return reject("Network error. Please try again.");
                    } else {
                        option.id = result.data.id;
                        return resolve(option);
                    }
                }).catch(error => {
                    reject("Network error. Please try again.");
                })
            });

        },

        /*

        // 批量上传
        uploadFile (item, list, isDirectory) {
            // 获取图片预览
            // 使用 FileReader 读取文件对象

            // new Promise((resolve, reject) => {
            //     const reader = new FileReader();
            //     const image = new Image();
            //     const maxsize = 1024 * 1024 * 50; // 不能上传超过50M的图片

            //     image.onload = (event) => {
            //         item.image = image;
            //         item.width = image.width;
            //         item.height = image.height;
            //         resolve(item)
            //     };

            //     image.onerror = (event) => {
            //         reject('Failed to load image')
            //     };

            //     // 读取完毕后获取结果
            //     reader.onload = (event) => {
            //         image.src = event.target.result;
            //     };

            //     if (item.file.size > maxsize) {
            //         // 超过大小
            //         reject('The maximum upload file size is 50M.')
            //     } else {
            //         list.unshift(item);
            //         reader.readAsDataURL(item.file);
            //     }
            // })

            let maxsize = 1024 * 1024 * 50; // 不能上传超过50M的图片
            if (item.file.size > maxsize) {
                this.$uxMessage.error('The maximum upload file size is 50M.');
            } else {

                list.unshift(item);
                this.getFileInfo(item).then(item => {

                    return new Promise((resolve, reject) => {

                        const email = (this.userInfo || {}).email;
                        const folder = email ? Md5(email) : 'noemail';
                        const path = 'data/pod/file/' + folder;

                        const time = new Date().getTime();
                        const random = Math.random().toFixed(10).substr(2);
                        const name = time + "-" + random + "." + item.img_type;

                        const request = {
                            file: item.file,
                            name: name,
                            path: path.replace(/\/+$/, '') + '/',
                            onprogress (event) {
                                item.percent = 5 + parseInt(0.9 * event.percent);
                            },
                        };

                        this.$uploadToOSS(request, response => {
                            if (response.code === 0 && response.data) {
                                item.img_url = response.data || '';
                                resolve(item);
                            } else {
                                reject(response.msg || "Upload more than 10 times");
                            }
                        })
                    })

                }).then(item => {
                    // 生成缩略图
                    return this.$http("Drawer.createThumb", { fullname: item.img_url }).then((result) => {
                        if (!result || result.code !== 0) {
                            return Promise.reject("Failed to create thumbnail image");
                        } else {
                            item.preview_url = result.data;
                            return Promise.resolve(item);
                        }
                    }).catch(error => {
                        return Promise.reject("Failed to create thumbnail image");
                    })

                }).then(item => {
                    // 绑定
                    const request = {
                        folder_id: item.folder_id,
                        file_name: item.img_name,
                        file_url: item.img_url,
                        file_size: item.img_size,
                        width: item.width,
                        height: item.height,
                        img_type: item.img_type,
                        preview_url: item.preview_url,
                    };
                    return this.$http('Material.setMaterialBind', request).then(result => {
                        if (!result || result.code !== 0) {
                            return Promise.reject("Failed to bind image");
                        } else {
                            item.id = result.data.id;
                            return Promise.resolve(item);
                        }
                    });


                }).then(item => {
                    item.type = "";
                    item.percent = 100;
                    isDirectory && this.getFolders()
                }).catch(error => {
                    item.type = "error";
                    item.error = error || 'Failed to upload image';
                    this.$uxMessage.error(item.error);
                })
            }



        },

        // 选中文件上传
        selectFile () {
            let filebox = this.$refs.filebox;
            filebox.innerHTML = '<input type="file" multiple accept="image/jpeg,image/jpg,image/png">';
            filebox.querySelector("input").onchange = (event) => {
                const files = ((event || {}).target || {}).files || [];
                const time = new Date().getTime();
                const isOutside = this.activeInfo == this.unclassify;
                const isDirectory = !!this.activeInfo.id;
                const list = isOutside ? this.unclassify.list : isDirectory ? this.directory.list : [];

                [...files].map((file, index) => {

                    // this.unclassify.list.unshift(...insert);
                    const item = {
                        type: "upload",
                        folder_id: this.activeInfo.id || 0,
                        id: time + "-" + index,
                        img_type: file.type.replace("image/", ""),
                        img_name: file.name,
                        img_size: file.size,
                        img_url: "",
                        preview_url: '',
                        width: 1,
                        height: 1,
                        file: file,
                        image: null,
                        percent: 5,
                        error: '',
                    };

                    this.uploadFile(item, list, isDirectory);
                });

                if (this.activeInfo == this.searching) {
                    // 在搜索容器内
                    // 先退出容器
                    this.searching.name = "";
                    this.keywords = "";
                }

                // 在最外层
                this.$nextTick((e) => {
                    if (this.$refs.unclassify && isOutside) {
                        let vm = this.$refs.unclassify;
                        let el = vm.$el;
                        let rect = el.getBoundingClientRect();

                        // 滚动到对应位置
                        window.scrollTo(0, rect.top - 50);
                    } else {
                        window.scrollTo(0, 0);
                    }
                });

            };
            filebox.querySelector("input").click();
        },

        */

    },
};
</script>
<style lang="scss" scoped>
.uploader {
    padding: 40px 24px 33px;
    .drag-box {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 460px;
        height: 200px;
        background: #fafafa;
        border-radius: 6px;
        border: 1px dashed #cccccc;

        svg {
            width: 32px;
            height: 32px;
            pointer-events: none;
        }
        span {
            margin-top: 4px;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #9e9e9e;
            line-height: 16px;
            pointer-events: none;
        }

        &.active {
            border-color: #239ac2;
            background-color: rgba(237, 251, 255, 0.4);
            span {
                color: #239ac2;
            }
            svg {
                color: #239ac2;
            }
        }
    }

    .or {
        position: relative;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #9e9e9e;
        line-height: 16px;
        height: 16px;
        margin-top: 32px;

        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            right: 0;
            height: 1px;
            background: #f0f0f0;
            transform: translateY(-50%);
        }

        &::after {
            content: 'Or';
            position: absolute;
            width: 40px;
            background-color: #fff;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }
    }

    .input {
        margin-top: 32px;
        position: relative;
        display: flex;
        justify-content: center;
        label {
            width: 260px;
            height: 40px;
            position: relative;
            overflow: hidden;
            background: #ea4c89;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;

            &:hover {
                background: #c94175;
            }
        }
        input {
            position: absolute;
            right: 0;
            top: 0;
            width: 300%;
            height: 300%;
            font-size: 99em;
            opacity: 0;
            cursor: pointer;
        }
        span {
            font-size: 14px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #ffffff;
        }
        svg {
            width: 18px;
            height: 18px;
            margin-right: 4px;
            color: #fff;
        }
    }

    & > p {
        margin-top: 32px;
        display: flex;
        justify-content: center;
        align-items: center;

        svg {
            width: 14px;
            height: 14px;
            border-radius: 14px;
            color: #a8a8a8;
            margin-right: 4px;
        }
        span {
            font-size: 12px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #757575;
            line-height: 14px;
        }
    }
}

// .moveto::v-deep > .dialog-layout > .dialog-content h2 {
//     padding-left: 20px;
//     padding-right: 20px;
// }
// .dialog-folder {
//     width: 320px;
//     height: 374px;
//     padding: 20px 0;
//     box-sizing: border-box;
//     display: flex;
//     flex-direction: column;

//     ul {
//         display: flex;
//         flex-direction: column;
//         flex: 1;
//         overflow: auto;
//         padding: 0 20px;

//         li {
//             margin: 6px 0;
//             height: 32px;
//             box-sizing: border-box;
//             background: #ffffff;
//             border-radius: 4px;
//             border: 1px solid #c6c6c6;
//             font-size: 14px;

//             color: #555555;
//             line-height: 30px;
//             text-align: center;
//             display: flex;
//             align-items: center;
//             justify-content: center;
//             cursor: pointer;
//             svg {
//                 width: 16px;
//                 height: 16px;
//                 margin-right: 8px;

//                 fill: #48c4ef;
//                 stroke: #48c4ef;
//             }

//             &:hover {
//                 color: #ea4c89;
//                 border-color: #ea4c89;
//             }

//             &:last-child {
//                 border: 1px solid #d9d9d9;
//                 color: #48c4ef;

//                 &:hover {
//                     color: #ea4c89;
//                     border-color: #ea4c89;
//                     svg {
//                         fill: #ea4c89;
//                         stroke: #ea4c89;
//                     }
//                 }
//             }

//             &.active {
//                 border-color: #ea4c89;
//             }
//         }
//     }

//     & > button {
//         margin: 24px 20px 8px;
//         width: auto;
//         height: 40px;
//     }
// }
</style>
